package com.bat.conf;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.BestAvailableRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.util.List;
import java.util.Random;

/**
 * @program: gateway
 * @description:
 * @author: zhoupengfei
 * @create: 2019-08-16 17:15
 **/
@Slf4j
@Configuration
public class IpUserHashRule extends BestAvailableRule {

    public static ThreadLocal<String> originHost=new ThreadLocal<>();
    public static  String originHostHeader="originHost";
    public static  String stable="stable";
    public static String dev;

    public static void main(String[] args) {
        InetUtilsProperties target = new InetUtilsProperties();
        InetUtils ipUtils=new InetUtils(target);
        InetAddress address=ipUtils.findFirstNonLoopbackAddress();
        log.info(JSONUtil.toJsonStr(address.getCanonicalHostName()));
    }

    public Server choose(ILoadBalancer lb, Object key) {
        log.info("步骤2");
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        }
        Server server = null;
        List<Server> reachableServers = lb.getReachableServers();

        if(reachableServers==null ||reachableServers.size()==0){
            log.warn("没有可用的服务");
            return null;
        }
        // 优先找和访问ip同源的服务
        if(originHost.get()!=null){
            //自定义策略生效
            for(Server serverl:reachableServers){
                if(serverl.getHost().equals(originHost.get())){
                    server=serverl;
                    log.info("host{},server{}",server.getHost(),JSONUtil.toJsonStr(server));
                    return  server;
                }
            }
        }
        //通过注册信息-找稳定的服务
        for(Server s:reachableServers){
            if(s.getMetaInfo()!=null){
                String meta=JSONUtil.toJsonStr(s);
               // log.info(meta);
                JSONObject metadata=JSONUtil.parseObj(meta).getJSONObject("instanceInfo").getJSONObject("metadata");
                if(metadata!=null && metadata.get(stable)!=null){
                    server=s;
                    log.info("host{},server{}",server.getHost(),JSONUtil.toJsonStr(server));
                    return  server;
                }
            }

        }

        //随机一个服务
        Random random=new Random();
        int index=reachableServers.size();
        server=reachableServers.get(random.nextInt(index));
        log.info("host{},server{}",server.getHost(),JSONUtil.toJsonStr(server));
        return  server;
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // TODO Auto-generated method stub

    }
}